package com.paradise.ytj.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.paradise.ytj.R;
import com.paradise.ytj.activity.MainActivity;
import com.paradise.ytj.activity.VideoActivity;
import com.paradise.ytj.bean.ContactInfo;
import com.paradise.ytj.bean.FinishEvent;
import com.paradise.ytj.helper.ContactDao;
import com.paradise.ytj.helper.RecordDao;
import com.paradise.ytj.utils.CameraUtils;
import com.paradise.ytj.utils.DialogUtils;
import com.paradise.ytj.view.CustomDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.List;

/**
 *
 */
public class RecordFragment extends Fragment implements View.OnClickListener, View.OnFocusChangeListener {

    private View inflate;
    private ListView lvFragmentAddressRecord;
    private RecordAdapter cAdapter;
    private RecordDao recordDao;
    private ImageView ivDelete;
    private ImageView ivClearRecord;
    private EditText etSearch;
    private TextView tvClearRecord;
    private LinearLayout llNotData;
    private ContactDao contactDao;
    private ListView lvFind;
    private List<ContactInfo> records;
    private RecordAdapter adapter;
    private Activity context;
    private RelativeLayout etRecord;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = getActivity();
        inflate = View.inflate(context, R.layout.fragment_record, null);
        initView();
        initData();
        initListener();
        return inflate;
    }

    /**
     * 初始化控件
     */
    private void initView() {
        lvFragmentAddressRecord = (ListView) inflate.findViewById(R.id.lv_fragment_address_record);
        lvFind = (ListView) inflate.findViewById(R.id.lv_fragment_address_find);
        llNotData = (LinearLayout) inflate.findViewById(R.id.ll_not_data);
        ivDelete = (ImageView) inflate.findViewById(R.id.iv_delete);
        ivClearRecord = (ImageView) inflate.findViewById(R.id.iv_clear_record);
        etSearch = (EditText) inflate.findViewById(R.id.et_record_search);
        etRecord = (RelativeLayout) inflate.findViewById(R.id.et_record);
        tvClearRecord = (TextView) inflate.findViewById(R.id.tv_clear_record);

    }

    /**
     * 初始化数据
     */
    private void initData() {
        EventBus.getDefault().register(this);
        recordDao = new RecordDao(context);
        contactDao = new ContactDao(context);
        records = recordDao.getAllRecords();
        cAdapter = new RecordAdapter(records);
        lvFragmentAddressRecord.setAdapter(cAdapter);
        lvFragmentAddressRecord.setItemsCanFocus(true);
        lvFind.setItemsCanFocus(true);
        if (records.size() > 0) {
            lvFragmentAddressRecord.setVisibility(View.VISIBLE);
            llNotData.setVisibility(View.INVISIBLE);
            ivClearRecord.setEnabled(true);

        } else {
            lvFragmentAddressRecord.setVisibility(View.INVISIBLE);
            llNotData.setVisibility(View.VISIBLE);
            ivClearRecord.setEnabled(false);
        }
    }

    /**
     * 初始化事件
     */
    private void initListener() {
        etSearch.setOnClickListener(this);
        ivDelete.setOnClickListener(this);
        ivClearRecord.setOnClickListener(this);
        ivClearRecord.setOnFocusChangeListener(this);
        etSearch.setOnFocusChangeListener(this);
        etSearch.addTextChangedListener(new ContactWatcher());
        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                lvFragmentAddressRecord.setSelection(0);
                lvFind.setSelection(0);
                if (hasFocus) {
                    //etRecord.setBackground(context.getResources().getDrawable(R.drawable.login_focus));
                } else {
                    etRecord.setBackground(context.getResources().getDrawable(R.drawable.et_bg));
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_delete:
                String search = etSearch.getText().toString();
                if (search.length() > 0) {
                    search = search.substring(0, search.length() - 1);
                    etSearch.setText(search);
                }
                break;

            case R.id.iv_clear_record:

                final CustomDialog customDialog = new CustomDialog(context);
                if (!getActivity().isFinishing()) {
                    customDialog.show();
                }
                View inflate = View.inflate(context, R.layout.dialog_clear_record, null);
                customDialog.getContentView().addView(inflate);
                customDialog.setTitleText(R.string.delete_record);
                customDialog.setDeclareText(R.string.delete_record_hint);
                customDialog.setOnCancelListener(new CustomDialog.OnCancelListener() {
                    @Override
                    public void onCancelClick() {
                        customDialog.dismiss();

                    }
                });
                customDialog.setOnSubmitListener(new CustomDialog.OnSubmitListener() {
                    @Override
                    public void onSubmitClick() {
                        recordDao.clearRecording();
                        records = recordDao.getAllRecords();
                        cAdapter = new RecordAdapter(records);
                        lvFragmentAddressRecord.setAdapter(cAdapter);
                        customDialog.dismiss();
                        lvFragmentAddressRecord.setVisibility(View.INVISIBLE);
                        llNotData.setVisibility(View.VISIBLE);
                    }
                });
                break;

            case R.id.et_record_search:
                etSearch.setInputType(InputType.TYPE_CLASS_TEXT);
                etSearch.requestFocus();
                InputMethodManager immm = (InputMethodManager) etSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                immm.showSoftInput(etSearch, 0);
                break;
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.iv_clear_record:
                if (hasFocus) {
                    tvClearRecord.setTextColor(context.getResources().getColor((R.color.add)));
                } else {
                    tvClearRecord.setTextColor(context.getResources().getColor((R.color.gray)));
                }
                break;
        }
    }

    class ContactWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().length() == 0) {
                records = recordDao.getAllRecords();
                cAdapter = new RecordAdapter(records);
                lvFragmentAddressRecord.setAdapter(cAdapter);
                lvFragmentAddressRecord.setVisibility(View.VISIBLE);
                lvFind.setVisibility(View.INVISIBLE);

            } else {
                lvFragmentAddressRecord.setVisibility(View.INVISIBLE);
                lvFind.setVisibility(View.VISIBLE);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {
            String text = s.toString();
            List<ContactInfo> findInfos = recordDao.findByText(text);
            adapter = new RecordAdapter(findInfos);
            lvFind.setAdapter(adapter);
        }
    }

    class RecordAdapter extends BaseAdapter implements View.OnFocusChangeListener {

        private List<ContactInfo> contactInfos;

        public RecordAdapter(List<ContactInfo> contactInfos) {
            this.contactInfos = contactInfos;
        }

        @Override
        public int getCount() {
            return contactInfos.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.record_item, null);
                holder = new ViewHolder();
                holder.tvAccount = (TextView) convertView.findViewById(R.id.tv_record_account);
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_record_name);
                holder.ivDelete = (ImageView) convertView.findViewById(R.id.iv_record_delete);
                holder.llRecord = (LinearLayout) convertView.findViewById(R.id.ll_record);
                holder.tvTime = (TextView) convertView.findViewById(R.id.tv_record_time);
                holder.ivAdd = (ImageView) convertView.findViewById(R.id.iv_record_add);
                holder.tvCallDuration = (TextView) convertView.findViewById(R.id.tv_record_calltime);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (position == contactInfos.size() - 1) {
                holder.llRecord.setNextFocusDownId(R.id.rb_record);
                holder.ivDelete.setNextFocusDownId(R.id.rb_record);
                holder.ivAdd.setNextFocusDownId(R.id.rb_record);


            }
            holder.tvName.setText(contactInfos.get(position).getName());
            holder.tvTime.setText(contactInfos.get(position).getTime());
            holder.tvAccount.setText(contactInfos.get(position).getNumber());
            holder.tvCallDuration.setText(contactInfos.get(position).getCallDutation());
            if (contactDao.findByAccount(contactInfos.get(position).getNumber())) {
                holder.ivAdd.setVisibility(View.INVISIBLE);
            }
            holder.ivAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final CustomDialog customDialog = new CustomDialog(context);
                    if (!getActivity().isFinishing()) {
                        customDialog.show();
                    }
                    View inflate = View.inflate(context, R.layout.dialog_add_contact, null);
                    final EditText etContactName = (EditText) inflate.findViewById(R.id.et_contact_name);
                    final EditText etContactAccount = (EditText) inflate.findViewById(R.id.et_contact_account);
                    etContactAccount.setText(contactInfos.get(position).getNumber());
                    ImageView ivDeleteAccount = (ImageView) inflate.findViewById(R.id.iv_delete_account);
                    ImageView ivDeleteName = (ImageView) inflate.findViewById(R.id.iv_delete_name);

                    customDialog.setTitleText(R.string.add_contact);
                    customDialog.getContentView().addView(inflate);
                    customDialog.setOnSubmitListener(new CustomDialog.OnSubmitListener() {
                        @Override
                        public void onSubmitClick() {
                            String account = etContactAccount.getText().toString().trim();
                            if (TextUtils.isEmpty(account)) {
                                Toast.makeText(context, R.string.account_hint, Toast.LENGTH_SHORT).show();
                                return;
                            }

                            String name = etContactName.getText().toString().trim();
                            if (TextUtils.isEmpty(name)) {
                                Toast.makeText(context, R.string.name_hint, Toast.LENGTH_SHORT).show();
                                return;
                            }

                            ContactDao dao = new ContactDao(context);
                            if (dao.findByAccount(account)) {
                                Toast.makeText(context, R.string.exist_account, Toast.LENGTH_SHORT).show();
                                return;
                            }

                            if (dao.add(name, account)) {
                                customDialog.dismiss();
                                etContactAccount.setText("");
                                etContactName.setText("");
                                Toast.makeText(context, R.string.add_success, Toast.LENGTH_SHORT).show();
                                cAdapter.notifyDataSetChanged();
                            } else {
                                Toast.makeText(context, R.string.add_fail, Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    customDialog.setOnCancelListener(new CustomDialog.OnCancelListener() {
                        @Override
                        public void onCancelClick() {
                            customDialog.dismiss();

                        }
                    });

                    etContactAccount.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            etContactAccount.setInputType(InputType.TYPE_CLASS_TEXT);
                            etContactAccount.requestFocus();
                            InputMethodManager imm = (InputMethodManager) etContactAccount.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.showSoftInput(etContactAccount, 0);
                        }
                    });
                    etContactName.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            etContactName.setInputType(InputType.TYPE_CLASS_TEXT);
                            etContactName.requestFocus();
                            InputMethodManager imm = (InputMethodManager) etContactName.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.showSoftInput(etContactName, 0);
                        }
                    });
                    ivDeleteAccount.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (etContactAccount.getText().toString().length() > 0) {
                                etContactAccount.setText(etContactAccount.getText().toString().substring(0, etContactAccount.getText().length() - 1));
                            }
                        }
                    });

                    ivDeleteName.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (etContactName.getText().toString().length() > 0) {
                                etContactName.setText(etContactName.getText().toString().substring(0, etContactName.getText().length() - 1));
                            }
                        }
                    });
                }
            });
            holder.ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    recordDao.delete(contactInfos.get(position).getTime());
                    if (!TextUtils.isEmpty(etSearch.getText().toString())) {
                        contactInfos.remove(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        contactInfos = recordDao.getAllRecords();
                        cAdapter.notifyDataSetChanged();
                        if (contactInfos.size() > 0) {
                            lvFragmentAddressRecord.setVisibility(View.VISIBLE);
                            llNotData.setVisibility(View.INVISIBLE);
                            ivClearRecord.setEnabled(true);
                        } else {
                            lvFragmentAddressRecord.setVisibility(View.INVISIBLE);
                            llNotData.setVisibility(View.VISIBLE);
                            ivClearRecord.setEnabled(false);
                        }
                    }

                }
            });
            if (holder.ivAdd.getVisibility() == View.INVISIBLE) {
                holder.ivDelete.setNextFocusRightId(R.id.rb_contact);
            } else {
            }
            holder.llRecord.setOnFocusChangeListener(this);
            holder.ivDelete.setOnFocusChangeListener(this);
            holder.ivAdd.setOnFocusChangeListener(this);
            holder.llRecord.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!MainActivity.isOnLine) {
                        Toast.makeText(context,R.string.offline_hint, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (CameraUtils.getNumber() == 0) {
                        Toast.makeText(context, R.string.no_camera_hint, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    RecordDao recordDao = new RecordDao(context);
                    ContactDao contactDao = new ContactDao(context);
                    String name = contactDao.getNameByAccount(contactInfos.get(position).getNumber());
                    if (name.equals("未知联系人")) {
                        name = contactInfos.get(position).getNumber();
                    }
                    Intent intent = new Intent(context, VideoActivity.class);
                    intent.putExtra("inout", "out");
                    intent.putExtra("object", name);
                    intent.putExtra("phone", contactInfos.get(position).getNumber());
                    startActivity(intent);
                    contactInfos = recordDao.getAllRecords();
                    cAdapter.notifyDataSetChanged();
                }
            });
            return convertView;
        }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
        }

        class ViewHolder {
            TextView tvName;
            TextView tvAccount;
            ImageView ivDelete;
            LinearLayout llRecord;
            TextView tvTime;
            ImageView ivAdd;
            TextView tvCallDuration;
        }
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getFinish(FinishEvent finishEvent) {
        if (recordDao != null && lvFragmentAddressRecord != null) {
            records = recordDao.getAllRecords();
            cAdapter = new RecordAdapter(records);
            lvFragmentAddressRecord.setAdapter(cAdapter);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
